package cc.loac.heba.tool;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.Bucket;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

import java.io.File;
import java.util.List;


/**
 * 获取腾讯云 CosClient
 */
public class MyCOSClient {

    private final static String COS_URL = "https://ldc-1251523367.cos.ap-beijing.myqcloud.com/";
    private final static String FOLDER_NAME = "Heba/";
    private final static String REGION_NAME = "ap-beijing";
    private final static String BUCKET_NAME = "ldc-1251523367";
    public static COSClient cosClient;

    /**
     * 获取腾讯云 CosClient 实例
     * @return COSClient
     */
    public static COSClient getCosClient() {
        if (cosClient == null) {
            // 初始化用户信息
            String secretId = "AKIDLXXK2WllV0FE1d1A4lFVWIp7AA1kIchY";
            String secretKey = "hAOOAgxylLiqjNlvra4JJ4bw4yd4IH3c";
            COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);

            // 设置存储桶地域信息
            Region region = new Region(REGION_NAME);
            ClientConfig clientConfig = new ClientConfig(region);

            // 建议使用 https 协议
            clientConfig.setHttpProtocol(HttpProtocol.https);
            cosClient = new COSClient(cred, clientConfig);
        }
        return cosClient;
    }

    /**
     * 上传文件
     * @param file File 对象
     * @param path 上传到存储桶中的路径，包括文件名和类型
     * @return 文件公共访问地址，失败返回空文本
     */
    public static String uploadFile(File file, String path) {
        // 指定文件上传到 COS 上的路径，即对象键。例如对象键为folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
        String key = "Heba/" + path;
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, key, file);
            PutObjectResult putObjectResult = getCosClient().putObject(putObjectRequest);
            return COS_URL + FOLDER_NAME + path;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 上传图像，默认上传到 image 文件夹
     * @param file File 对象
     * @param path 上传到存储桶中的路径，包括文件名和类型
     * @return 文件公共访问地址，失败返回空文本
     */
    public static String uploadImage(File file, String path) {
        return uploadFile(file, "image/" + path);
    }

    /**
     * 删除文件
     * @param path 存储桶中的路径，包括文件名和类型
     * @return 成功返回 0，否则返回 -1
     */
    public static boolean deleteFile(String path) {
        try {
            getCosClient().deleteObject(BUCKET_NAME, FOLDER_NAME + path);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
